import curses
import random

# 游戏设置
s = curses.initscr()
curses.curs_set(0)
sh, sw = s.getmaxyx()  # 屏幕高度和宽度
w = curses.newwin(sh, sw, 0, 0)  # 创建窗口
w.keypad(1)
w.timeout(100)  # 刷新时间

# 初始化蛇和食物
snk_x = sw // 4
snk_y = sh // 2
snake = [
    [snk_y, snk_x],
    [snk_y, snk_x - 1],
    [snk_y, snk_x - 2]
]
food = [sh // 2, sw // 2]
w.addch(int(food[0]), int(food[1]), curses.ACS_PI)

key = curses.KEY_RIGHT

while True:
    next_key = w.getch()
    key = key if next_key == -1 else next_key

    # 更新蛇的位置
    new_head = [snake[0][0], snake[0][1]]

    if key == curses.KEY_DOWN:
        new_head[0] += 1
    if key == curses.KEY_UP:
        new_head[0] -= 1
    if key == curses.KEY_LEFT:
        new_head[1] -= 1
    if key == curses.KEY_RIGHT:
        new_head[1] += 1

    # 检查边界和自撞
    if (new_head[0] in [0, sh] or
            new_head[1] in [0, sw] or
            new_head in snake):
        curses.endwin()
        quit()

    # 插入新头
    snake.insert(0, new_head)

    # 食物被吃掉
    if snake[0] == food:
        food = None
        while food is None:
            nf = [
                random.randint(1, sh - 1),
                random.randint(1, sw - 1)
            ]
            food = nf if nf not in snake else None
        w.addch(int(food[0]), int(food[1]), curses.ACS_PI)
    else:
        # 移动蛇
        tail = snake.pop()
        w.addch(int(tail[0]), int(tail[1]), ' ')

    # 画蛇头
    w.addch(int(snake[0][0]), int(snake[0][1]), curses.ACS_CKBOARD)

# 结束游戏
curses.endwin()
